package com.totoro.service;

import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/*
 * 该类的主要作用是为Spring Security提供一个经过用户认证后的UserDetails。
 *该UserDetails包括用户名、密码、是否可用、是否过期等信息。
 */
@Service
public class MyUserDetailService implements UserDetailsService {
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private UserRoleService userRoleService;

	/*
	@Autowired
	private UserCache userCache;
	*/

	// 加载用户通过用户名
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		System.out.println("username is :" + username);

		com.totoro.domain.User user = this.userService.uniqueResult("username", username);
		System.out.println("用户名为：" + user.getUsername());

		// 获得用户权限
		Collection<GrantedAuthority> auths = userRoleService
				.loadUserAuthorityByName(user);

		//boolean enables = true;
		// 账户过期否
		boolean accountNonExpired = true;
		// 证书过期否
		boolean credentialsNonExpired = true;
		// 账户锁定否
		boolean accountNonLocked = true;
		// 封装成spring security的user
		User userdetail = new User(username, user.getPassword(),
				user.getEnableToLogin(), accountNonExpired,
				credentialsNonExpired, accountNonLocked, auths);
		for (GrantedAuthority s : auths) {
			s.getAuthority();
		}
		System.out.println(auths);
		return userdetail;

	}

}
